const multer = require("@koa/multer");
const dayjs = require("dayjs");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid");
const { STATIC_PATH } = require("../config/path");

const uploadAvatar = multer({
  storage: multer.diskStorage({
    // 自定义文件地址
    destination(req, file, callback) {
      // 按照当前年月，创建好文件夹
      const dirName = dayjs().format("YYYYMM");
      const dirPath = `${STATIC_PATH}/uploads/${dirName}`;
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(`${STATIC_PATH}/uploads/` + dirName);
      }
      callback(null, `${STATIC_PATH}/uploads/${dirName}`);
    },
    // 自定义文件名称
    filename(req, file, callback) {
      console.log("file", file);
      const unit = file.originalname.split(".")[1];

      callback(null, `${uuidv4()}.${unit}`);
    },
  }),
});

function norUpLoad() {
  const uploadObj = multer({
    storage: multer.diskStorage({
      // 自定义文件地址
      destination(req, file, callback) {
        // 按照当前年月，创建好文件夹
        const dirName = dayjs().format("YYYYMM");
        const dirPath = `${STATIC_PATH}/uploads/${dirName}`;
        if (!fs.existsSync(dirPath)) {
          fs.mkdirSync(dirPath);
        }
        callback(null, dirPath);
      },
      // 自定义文件名称
      filename(req, file, callback) {
        const unit = file.originalname.split(".")[1];
        callback(null, `${uuidv4()}.${unit}`);
      },
    }),
  });

  return uploadObj.single("file");
}

function blogUpLoad() {
  const uploadObj = multer({
    storage: multer.diskStorage({
      // 自定义文件地址
      destination(req, file, callback) {
        // 按照当前年月，创建好文件夹
        const dirName = dayjs().format("YYYYMM");
        const dirPath = `${STATIC_PATH}/blogs/${dirName}`;
        if (!fs.existsSync(dirPath)) {
          fs.mkdirSync(dirPath);
        }
        callback(null, dirPath);
      },
      // 自定义文件名称
      filename(req, file, callback) {
        const unit = file.originalname.split(".")[1];
        callback(null, `${uuidv4()}.${unit}`);
      },
    }),
  });

  return uploadObj.single("file");
}

const handleFile1 = norUpLoad();
const handleFile2 = blogUpLoad();

module.exports = {
  handleFile1,
  handleFile2,
};
